package com.wis.bolt.risk;

import com.wis.TopologyDrive;
import org.apache.commons.lang.StringUtils;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @Description: traffic_wis
 * @author: fan
 * @Date: Created in 2018/12/19 10:43
 * @Modified By:
 */
public class ZongHeShouJiBolt extends BaseRichBolt {
    private OutputCollector collector;
    private static Queue tupleQueue = new ConcurrentLinkedQueue();
    private static String typeProduce;

    @Override
    public void prepare(Map map, TopologyContext context, OutputCollector collector) {
        this.collector = collector;
        typeProduce = map.get(TopologyDrive.TYPE_PRODUCE).toString();
    }

    @Override
    public void execute(Tuple tuple) {
        String key = tuple.getStringByField("key");
        String id = tuple.getStringByField("id");
        try {
            //declarer.declare(new Fields("key", "id", "value", "xiangtai"));
            if (StringUtils.isNotBlank(key)) {
                if (id.equals("over")) {
                    if (tupleQueue.size() > 1)
                        this.collector.emit(new Values("1" + typeProduce + "2" + key + "00", StringUtils.join(tupleQueue, "_")));
                    tupleQueue.clear();
                } else {
                    tupleQueue.add(tuple.getStringByField("value"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.collector.ack(tuple);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("key", "value"));
    }
}
